package com.example.magnet.util;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class ContextUtil implements ApplicationContextAware {

    private ApplicationContext context;

    private static ContextUtil instance;

    public ContextUtil() {
        instance = this; //赋值给静态对象
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    //提供静态访问
    public static <T> T getBean(Class<T> cls) {
        return instance.context.getBean(cls);
    }

    //提供静态访问
    public static <T> T getBean(String name) {
        return (T) instance.context.getBean(name);
    }

    /**
     * 获取当前请求
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = getRequestAttributes();
        if (requestAttributes != null)
            return requestAttributes.getRequest();
        return null;
    }

    /**
     * 获取当前响应
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = getRequestAttributes();
        if (requestAttributes != null)
            return requestAttributes.getResponse();
        return null;    }

    public static ServletRequestAttributes getRequestAttributes() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes;
    }
}
